﻿using System;
using System.Web.UI.WebControls;

namespace ECommerce.Administration.Controls
{
	public partial class ShippingMethodList : AdminBaseUsercontrol
	{
		private Service.IShippingMethodService _ShippingMethodService;

		protected void Page_Load(object sender, EventArgs e)
		{
			if(!IsPostBack)
			{
				BindData();
			}
		}

		protected void GridShippingMethod_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if(e.Row.RowType == DataControlRowType.Header)
			{
				e.Row.Cells[1].Text = GetLocalResourceString("Admin.ShippingMethodList.NameHeader");
				e.Row.Cells[2].Text = GetLocalResourceString("Admin.ShippingMethodList.ActiveHeader");
				e.Row.Cells[3].Text = GetLocalResourceString("Admin.ShippingMethodList.DisplayOrderHeader");
			}

			if(e.Row.DataItem != null)
			{
				var item = e.Row.DataItem as Data.Entity.ShippingMethod;

				HyperLink HyperLinkShippingMethod = e.Row.FindControl("HyperLinkShippingMethod") as HyperLink;

				HyperLinkShippingMethod.NavigateUrl = "~/Administration/EditShippingMethod.aspx?shippingmethodid=" + item.ShippingMethodID.ToString();
				HyperLinkShippingMethod.Text = item.Name;
			}
		}

		private void BindData()
		{
			if (_ShippingMethodService == null)
			{
				_ShippingMethodService = new Service.ShippingMethodService();
			}

			var data = _ShippingMethodService.GetAllShippingMethod();

			GridShippingMethod.DataSource = data;
			GridShippingMethod.DataBind();
		}

		public void DeleteSelectedShippingMethods()
		{
			if (_ShippingMethodService == null)
			{
				_ShippingMethodService = new Service.ShippingMethodService();
			}

			foreach (GridViewRow item in GridShippingMethod.Rows)
			{
				var chBox = item.FindControl("cbShippingMethod") as CheckBox;
				var hfShippingMethodID = item.FindControl("hfShippingMethodID") as HiddenField;

				bool isChecked = chBox.Checked;
				int shippingMethodID = int.Parse(hfShippingMethodID.Value);

				if(isChecked)
				{
					_ShippingMethodService.DeleteShippingMethod(shippingMethodID);
				}
			}

			BindData();
		}
	}
}